package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.AttendanceRecord;
import org.example.entity.VacationApplication;
import org.example.models.R;
import org.example.service.AttendanceRecordService;
import org.example.service.VacationApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @Author: 鸢一折纸
 * @Email: 3498881048@qq.com
 * @Date: 2025/09/15 8:47
 * @Description:
 **/

@RestController
@RequestMapping("/vacationApplication")
public class VacationApplicationController {

    @Autowired
    private VacationApplicationService vacationApplicationService;
    @Autowired
    private AttendanceRecordService attendanceRecordService;

    @GetMapping("/page")
    public R<Page<VacationApplication>> page(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "4") int size,
            @RequestAttribute("userId") Integer userId,
            @RequestParam(name = "applicationDate", required = false) String applicationDate
    ) {
        QueryWrapper<VacationApplication> query = new QueryWrapper<>();
        query.lambda().eq(VacationApplication::getUserId, userId);

        if (applicationDate != null && !applicationDate.isEmpty()) {
            query.lambda().like(VacationApplication::getApplicationDate, applicationDate);
        }

        query.lambda().orderByDesc(VacationApplication::getUpdatedAt);

        Page<VacationApplication> page = new Page<>(current, size);
        vacationApplicationService.page(page, query);
        return R.success(page);
    }

    @GetMapping("/vacationDetails")
    public R<Page<VacationApplication>> vacationDetails(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "4") int size,
            @RequestAttribute("userId") Integer userId,
            @RequestParam(name = "applicationDate", required = false) String applicationDate
    ) {
        QueryWrapper<VacationApplication> query = new QueryWrapper<>();
        query.lambda().eq(VacationApplication::getUserId, userId);

        if (applicationDate != null && !applicationDate.isEmpty()) {
            query.lambda().eq(VacationApplication::getApplicationDate, applicationDate);
        }

        query.lambda().orderByDesc(VacationApplication::getUpdatedAt);

        Page<VacationApplication> page = new Page<>(current, size);
        vacationApplicationService.page(page, query);
        return R.success(page);
    }

    @PostMapping("/insert")
    public R<String> insert(@RequestBody List<VacationApplication> vacationApplications,
                            @RequestAttribute("userId") Integer userId) {
        if (vacationApplications == null || vacationApplications.isEmpty()) {
            return R.error("请至少提交一条调休记录");
        }

        // 添加重复检查
        for (VacationApplication vacation : vacationApplications) {
            if (isDuplicateVacationApplication(vacation, userId)) {
                return R.error("存在重复的调休申请");
            }

            // 检查考勤记录状态，只有未签到才能调休
            if (!checkAttendanceStatus(vacation, userId)) {
                return R.error("该日期考勤状态不支持调休申请");
            }

            vacation.setUserId(userId);
        }

        boolean saveBatch = vacationApplicationService.saveBatch(vacationApplications);
        if (!saveBatch) {
            return R.error("调休申请提交失败");
        } else {
            for (VacationApplication vacation2 : vacationApplications) {
                boolean update = true;
                if (vacation2.getVacationPeriod().equals("上午")) {
                    update = attendanceRecordService.update(
                            Wrappers.<AttendanceRecord>lambdaUpdate()
                                    .set(AttendanceRecord::getMorningStatus, "调休")
                                    .eq(AttendanceRecord::getUserId, userId)
                                    .eq(AttendanceRecord::getRecordDate, vacation2.getVacationDate()));
                } else if (vacation2.getVacationPeriod().equals("下午")) {
                    update = attendanceRecordService.update(
                            Wrappers.<AttendanceRecord>lambdaUpdate()
                                    .set(AttendanceRecord::getAfternoonStatus, "调休")
                                    .eq(AttendanceRecord::getUserId, userId)
                                    .eq(AttendanceRecord::getRecordDate, vacation2.getVacationDate()));
                } else {
                    update = attendanceRecordService.update(
                            Wrappers.<AttendanceRecord>lambdaUpdate()
                                    .set(AttendanceRecord::getMorningStatus, "调休")
                                    .set(AttendanceRecord::getAfternoonStatus, "调休")
                                    .eq(AttendanceRecord::getUserId, userId)
                                    .eq(AttendanceRecord::getRecordDate, vacation2.getVacationDate()));
                }

                if (!update) {
                    return R.error("调休申请提交失败");
                }
            }
        }

        return R.success("调休申请成功");
    }

    /**
     * 检查考勤记录状态，只有未签到才能调休
     */
    private boolean checkAttendanceStatus(VacationApplication vacation, Integer userId) {
        // 获取调休日期和时段
        Date vacationDate = vacation.getVacationDate();
        String vacationPeriod = (String) vacation.getVacationPeriod();

        // 查询考勤记录
        QueryWrapper<AttendanceRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("record_date", vacationDate);

        AttendanceRecord record = attendanceRecordService.getOne(wrapper);
        if (record == null) {
            // 如果没有考勤记录，默认允许调休
            return true;
        }

        // 检查对应时段是否为未签到状态
        if ("上午".equals(vacationPeriod)) {
            return "未签到".equals(record.getMorningStatus()) || record.getMorningStatus() == null;
        } else if ("下午".equals(vacationPeriod)) {
            return "未签到".equals(record.getAfternoonStatus()) || record.getAfternoonStatus() == null;
        } else if ("全天".equals(vacationPeriod)) {
            return ("未签到".equals(record.getMorningStatus()) || record.getMorningStatus() == null) &&
                    ("未签到".equals(record.getAfternoonStatus()) || record.getAfternoonStatus() == null);
        }

        return false;
    }

    /**
     * 检查是否存在重复或冲突的调休申请
     */
    private boolean isDuplicateVacationApplication(VacationApplication vacation, Integer userId) {
        QueryWrapper<VacationApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("vacation_date", vacation.getVacationDate());

        // 如果是更新操作，需要排除当前记录本身
        if (vacation.getVacationId() != null) {
            queryWrapper.ne("vacation_id", vacation.getVacationId());
        }

        List<VacationApplication> existingApplications = vacationApplicationService.list(queryWrapper);

        String newPeriod = (String) vacation.getVacationPeriod();

        for (VacationApplication existing : existingApplications) {
            String existingPeriod = (String) existing.getVacationPeriod();

            // 检查完全相同的时段
            if (newPeriod.equals(existingPeriod)) {
                return true; // 相同时段重复
            }

            // 检查时段冲突
            if ("全天".equals(newPeriod) || "全天".equals(existingPeriod)) {
                return true; // 全天与任何时段都冲突
            }
        }

        return false;
    }

}
